# -*- coding: UTF-8 -*- 
from BeautifulSoup import BeautifulSoup
import urllib2
from deal_info_web import *

def deal_city(tuan, city):
    (f_id, d_id, orig) = judge_begin(tuan, city)

    f_url = urllib2.urlopen('http://www.zhaozhe.com/%s/index.html' % (city))

    soup = BeautifulSoup(f_url.read())

    f_xml = open('%sxml/%s_%s.xml' % (get_home_dir(), tuan, city), 'w')
    
    f_xml.write('<deals>\n')
    
    deal_id = soup.find(attrs={'class':'renren'})['href'].split('link=')[1].replace('http%3a%2f%2fwww.zhaozhe.com%2fshare%2fbeijing%2fr0%2f', '').replace('.html', '')
    if not judge(f_id, d_id, deal_id):
	f_xml.write('\t' + '<deal>\n')
	deal_info_source(f_xml, 'zhaozhe', '找折'.decode('utf-8'), 'http://www.zhaozhe.com/', 'http://www.zhaozhe.com/')

	f_xml.write('\t' * 2 + '<city>%s</city>\n' % city)

	deal_info_add(f_xml, 'id', deal_id, 2)
	deal_title = soup.find(attrs={'class':'deal-title'}).h1.contents[2]
	deal_info_add(f_xml, 'name', deal_title, 2)
	deal_info_cats(f_xml, deal_title)
	deal_vendor_name = soup.find(attrs={'class':'clientinfo'}).h2.contents[0].replace('\r', '').replace('\n', '').replace(' ', '')
	deal_info_vendor(f_xml, deal_vendor_name)
	deal_info_time(f_xml)
	deal_value = soup.find(attrs={'class':'discount-font'}).contents[0].replace('\r', '').replace('\n', '').replace(' ', '').replace('¥'.decode('utf-8'), '')
	deal_info_add(f_xml, 'o_price', deal_value, 2)
	deal_price = soup.find(attrs={'class':'discount-price'}).contents[0].replace('\r', '').replace('\n', '').replace(' ', '').replace('¥'.decode('utf-8'), '')
	deal_info_add(f_xml, 'c_price', deal_price, 2)
	deal_info_discount_and_save_money(f_xml, deal_price, deal_value)
	deal_img = 'http://www.zhaozhe.com' + soup.find(attrs={'id':'img_deals'}).img['src']
	deal_info_img(f_xml, deal_img)
	deal_url = 'http://www.zhaozhe.com/%s/%s.html' % (city, deal_id)
	deal_info_add(f_xml, 'url', deal_url, 2)

	f_xml.write('\t' + '</deal>\n')

    f_xml.write(orig[8 : ])

    f_xml.close()
    f_id.close()

    judge_end(tuan, city)



deal_city('zhaozhe', 'beijing')
